package com.sjh.lib_app.utils;


import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * RxJava 工具类
 * Created by LinXiao on 2016-07-24.
 */
public class RxJavaUtil {
    private static Disposable disposable;
    /**
     * 倒计时，单位 s，返回回调在主线程
     * @param seconds 倒计时秒数
     * */
    public static Observable<Integer> countDown(final int seconds) {
        return Observable.interval(0, 1, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .take(seconds)
        .map(increaseTime -> seconds - increaseTime.intValue()-1);
    }


    /**
     * 倒计时，单位 s，返回回调在主线程
     * @param seconds 倒计时秒数
     * @param listener onNext回调
     * */
    public static Observable<Integer> countDown(final int seconds,OnNextListener listener) {
        Observable<Integer> observable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .take(seconds)
                .map(increaseTime -> seconds - increaseTime.intValue() - 1);
        observable.subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(Integer integer) {
                listener.onNext(integer);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        return observable;
    }

    /**
     * 切断订阅事件
     */
    public static void dispose(){
        if (disposable != null)
            disposable.dispose();
    }
}